import asyncio
import time

import websocket
import json

from common.exchanges.deribit import DBTUserDataWsCatcher
from common.exchanges.entities import ApiAuthInfo

CLIENT_ID = 'c5KuWeL6'  # 填入你的access_key
CLIENT_SECRET = 'GwLmv-Yujahr-_s2dBUOsbMpEpaPKY9PdJ1YK4JDSwc'  # 填入你的secret_key


def on_message(ws, message):
    # 解析接收到的消息
    data = json.loads(message)
    print('Received data:', data)


def on_error(ws, error):
    print('Error:', error)


def on_close(ws):
    print('Connection closed')


def on_open(ws):
    # 订阅你需要的私有通信频道
    params = {
        "jsonrpc": "2.0",
        "id": 42,
        "method": "public/auth",
        "params": {
            "grant_type" : "client_credentials",
            "client_id" : CLIENT_ID,
            "client_secret" : CLIENT_SECRET
        }
    }
    ws.send(json.dumps(params))

    ws.send(json.dumps({
        "jsonrpc": "2.0",
        "id": 45,
        "method": "/private/get_account_summaries",
        "params": {}
    }))

    ws.send(json.dumps({
        "jsonrpc": "2.0",
        "id": 47,
        "method": "/private/subscribe",
        "params": {
            "channels": ["user.portfolio.any", "user.trades.btc"]
        }
    }))


def create_ws_connection():

    url = "wss://test.deribit.com/ws/api/v2"  # Deribit websocket URL
    websocket.enableTrace(True)
    # 创建websocket连接
    ws = websocket.WebSocketApp(url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()


def run_user_data_catcher():
    auth_info = ApiAuthInfo(api_key=CLIENT_ID, api_secret=CLIENT_SECRET)
    catcher = DBTUserDataWsCatcher(auth_info, env='test')
    catcher.run()

    for _ in range(7200):
        time.sleep(5)
        summaries = catcher.account_summaries()
        summary = [i for i in summaries if i.margin_currency == 'BTC']
        # print(summary[0])

        open_orders = catcher.open_orders()
        print(open_orders)


def run_multi_coro():
    tasks = []
    for _ in range(10):
        tasks.append(asyncio.sleep(1))
    g_task = asyncio.gather(*tasks)
    s = time.time()
    asyncio.get_event_loop().run_until_complete(g_task)
    print(f'token {time.time() - s}')


if __name__ == '__main__':
    run_user_data_catcher()
